#!/usr/bin/env python
# coding=utf-8
'''
Author: 以谁为师
Website: attacker.club
Date: 2022-01-03 17:40:17
LastEditTime: 2022-01-03 18:03:21
Description: 
'''
from rest_framework import status
from rest_framework.exceptions import APIException
from rest_framework.permissions import BasePermission

from utils.custom_log   import log_start
logger = log_start('Rbac')


class UserLock(APIException):
    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = '用户已被锁定,请联系管理员'
    default_code = 'not_authenticated'
    logger.error("用户已被锁定,请联系管理员")

    #  "User account is disabled."



class RbacPermission(BasePermission):
    """
    自定义Rbac权限认证
    """
    

    def has_permission(self, request, view):
        logger.info("开始Rbac认证检测")

        # 验证用户是否被锁定
        if not request.user.is_active:
            raise UserLock()
        
        if 'admin' in request.user.roles.values_list('name', flat=True):
            logger.info("admin 放行")
            return True

        else:
            logger.error("Rbac认证检测不通过")


